package cn.itsource.org.service.impl;

import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.util.PageList;
import cn.itsource.basic.util.TreeUtil;
import cn.itsource.org.domain.Department;
import cn.itsource.org.mapper.DepartmentMapper;
import cn.itsource.org.query.DepartmentQuery;
import cn.itsource.org.service.IDepartmentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department,DepartmentQuery> implements IDepartmentService {
    @Autowired
    private DepartmentMapper mapper;


    @Override
    public List<Department> findParentDepts() {
        return mapper.findParentDepts();
    }

    @Override
    public void batchDelete(Long[] ids) {
        mapper.batchDelete(ids);
    }

    @Override
    public List<Department> treeList() {
        //1.查询所有的部门对象集合
        List<Department> departments = mapper.selectAll();

        //2.使用工具类的方法
        List<Department> list = TreeUtil.getTree(departments);

        return list;
    }

    @Override
    public PageList<Department> findPage(DepartmentQuery query) {
        //调用分页方法
        PageHelper.startPage(query.getPage(),query.getSize());
        //调用查询方法
        List<Department> list = mapper.findPage(query);
        //封装分页数据
        PageInfo<Department> pageInfo = new PageInfo<>(list);
        //封装自定义数据对象
        PageList<Department> pageList = new PageList<>(pageInfo.getTotal(), pageInfo.getList());

        return pageList;
    }



    @Override
    public void saveOrUpdate(Department department) {
        if(department.getId() == null){
            //新增操作
            mapper.insertSelective(department);
            //调用方法
            makeParentDept(department);
            //修改这个对象
            mapper.updateByPrimaryKey(department);
        }else{
            //调用方法
            makeParentDept(department);
            //修改操作
            mapper.updateByPrimaryKey(department);
        }
    }


    private void makeParentDept(Department department) {
        Long[] parentIds = department.getParentIds();//3 8 10  // /3/8/10
        if (parentIds != null && parentIds.length > 0) {

            //1.设置parentId的值
            Long parentId = parentIds[parentIds.length - 1];
            department.setParentId(parentId);

            //2.循环  用得快捷提示:输入iter
            StringBuilder dirPath = new StringBuilder("");
            for (Long id : parentIds) {
                dirPath.append("/").append(id);
            }
            //3.加上自己的主键id值
            dirPath.append("/").append(department.getId()); //3/8/10/203
            department.setDirPath(dirPath.toString());

        } else {
            department.setParentId(null);
            department.setDirPath("/" + department.getId());
        }
    }


}
